//
//  ShoppingOfCartVC.m
//  EJLX
//
//  Created by adc on 15/11/11.
//  Copyright © 2015年 江苏一键联信息科技有限公司. All rights reserved.
//

#import "ShoppingOfCartVC.h"
#import "shoppingTableViewCell.h"
#import "ShoppingCarEditVC.h"
#import "QueRenDingDanViewController.h"
#import "ShangPinModel.h"
//#import "ShoppingHeaderView.h"
//@interface ShoppingOfCartVC ()


@implementation ShoppingOfCartVC
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    _price = 0;
    [_tableViewShopping reloadData];

    [HttpsManager getGouWuCheList:^(ShoppingCar *car) {
        self.shoppingCar = car;
        if (self.shoppingCar.sectionArr.count == 0) {
            SHOW_ALERT(@"还没有商品，去购物！")
        }else{
        
            _selectArray = [NSMutableArray array];
            
            for (int i = 0; i <self.shoppingCar.sectionArr.count; i++) {
                NSMutableDictionary *sectionDict = [NSMutableDictionary dictionary];
                NSMutableDictionary *rowDict = [NSMutableDictionary dictionary];
                [sectionDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_isSelect",i ]];
                
                CarSection *sectionGoods = self.shoppingCar.sectionArr[i];
                for (int a =0 ; a<sectionGoods.itemsArr.count;a++) {
                    
                    [rowDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_%drow",i ,a]];
                    [rowDict setObject:@"0" forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",i ,a]];
                    
                    
                }
                [sectionDict setObject:rowDict forKey:[NSString stringWithFormat:@"%dsection",i]];
                [_selectArray addObject:sectionDict];
            }
            [_tableViewShopping reloadData];

 
        }
        
  

 }];

   }
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
       
    [self creatNav];

    _isBtnSelectAll = NO;
    _isSectionBtn = NO;


}


-(void)creatNav{
    
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, WIDE, 44)];
    navView.backgroundColor = RGB_COLOR(0x00c49f);
    [self.view addSubview:navView];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(10, 7, 30, 30);
    leftBtn.layer.cornerRadius = 20;
    [leftBtn setImage:[UIImage imageNamed:@"返回箭头"] forState:UIControlStateNormal] ;
    [leftBtn addTarget:self action:@selector(backBtn) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:leftBtn];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(WIDE/2-60, 7, 120, 30  )];
    title.text = @"购物车";
    title.textAlignment = NSTextAlignmentCenter;
    title.textColor = [UIColor whiteColor];
    [navView addSubview:title];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(WIDE-50, 7, 40, 30);
    rightBtn.layer.cornerRadius = 20;
    [rightBtn setTitle:@"编辑" forState:UIControlStateNormal] ;
    [rightBtn addTarget:self action:@selector(editBtn) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:rightBtn];
   
}

-(void)backBtn{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)editBtn{
    ShoppingCarEditVC *VC = [[ShoppingCarEditVC alloc] init];
    VC.shop = self.shoppingCar;
    //VC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:VC animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.shoppingCar.sectionArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_tableViewShopping.dataSource == 0) {
        _tableViewShopping.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    CarSection *sectionGoods = self.shoppingCar.sectionArr[section];

    return sectionGoods.itemsArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

        return 100;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    
   
    shoppingTableViewCell *cell = nil;
    //cell = [tableView cellForRowAtIndexPath:indexPath];
   cell = [tableView dequeueReusableCellWithIdentifier:@"gouwuche1" ];
    cell = [[NSBundle mainBundle] loadNibNamed:@"shoppingTableViewCell" owner:nil options:nil][0];
    CarSection *sectionGoods = self.shoppingCar.sectionArr[indexPath.section];
        ShoppingCarItem *item = sectionGoods.itemsArr[indexPath.row];
    
    
    
    [cell.cell1Image sd_setImageWithURL:[NSURL URLWithString:item.image] placeholderImage:[UIImage imageNamed:@"笑脸.jpg"]];
    cell.cell1NameLB.text = item.name;
    cell.cell1YanSeLB.text = item.desc;
    
    NSDictionary *dic = @{NSStrikethroughStyleAttributeName:[NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.2f",item.price*0.01] attributes:dic];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, str.length)];
  
    cell.cell1OldPrice.attributedText = str;
 
   cell.cell1PriceLB.text = [NSString stringWithFormat:@"%.2f",item.discountPrice*0.01];
    cell.cell1NumLB.text = [NSString stringWithFormat:@"X%d",item.count];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
 
    NSMutableDictionary *sectionDict = [_selectArray[indexPath.section] objectForKey:[NSString stringWithFormat:@"%dsection",(int)indexPath.section]];
    NSString * isSeclect = [_selectArray[indexPath.section] objectForKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)indexPath.section]];
  
    if ([isSeclect isEqualToString:@"NO"]) {
        for (int i = 0; i <sectionDict.allKeys.count; i++) {
          
            [sectionDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)indexPath.section,(int)indexPath.row]];
            [sectionDict setObject:@"0" forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)indexPath.section,(int)indexPath.row]];

        }
       }else{
           for (int i = 0; i <sectionDict.allKeys.count; i++) {
            [sectionDict setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)indexPath.section,(int)indexPath.row]];
               CarSection *sectionGoods = self.shoppingCar.sectionArr[indexPath.section];
                ShoppingCarItem *item = sectionGoods.itemsArr[indexPath.row ];
               [sectionDict setObject:[NSString stringWithFormat:@"%.2f",item.count*item.discountPrice*0.01] forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)indexPath.section,(int)indexPath.row]];
              
           }
        
    }
    
  
    if ([[sectionDict objectForKey:[NSString stringWithFormat:@"%dsection_%drow",(int )indexPath.section,(int)indexPath.row]] isEqualToString:@"YES"]) {
        cell.cell1Btn.selected = YES;
        [cell.cell1Btn setImage:[UIImage imageNamed:@"购物车选中"] forState:UIControlStateSelected ];
   
    }else{
        cell.cell1Btn.selected = NO;
        [cell.cell1Btn setImage:[UIImage imageNamed:@"购物车未选择"] forState:UIControlStateNormal];
      
    }
    int b = 0 ,c =0;
    for ( int r = 0; r< sectionDict.allKeys.count/2; r++) {
        
        b = [[sectionDict  objectForKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int )indexPath.section,r]]intValue];
        c =c +b;
        _allPrice.text = [NSString stringWithFormat:@"¥:%d",c];
        
    }
    cell.cell1Btn.tag = indexPath.row+(indexPath.section*[(NSMutableDictionary *)[_selectArray[indexPath.section]allKeys] count ]);
    [cell.cell1Btn addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
   

  return cell;

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
   
    CarSection *sectionCar = [self.shoppingCar.sectionArr objectAtIndex:section];

    
    UIView *vc = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDE, 30)];
    vc.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = 10000+section;
    btn.frame = CGRectMake(5, 9, 25, 25);
   
     NSString *  isSeclect = [_selectArray[section] objectForKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)section]];
 
    if ([isSeclect isEqualToString:@"YES"]) {
    
        [btn setImage:[UIImage imageNamed:@"购物车选中"] forState:UIControlStateNormal ];

    }else{
        [btn setImage:[UIImage imageNamed:@"购物车未选择"] forState:UIControlStateNormal];
    }
  
 
    [btn addTarget:self action:@selector(selectHeaderBtn:) forControlEvents:UIControlEventTouchUpInside];
    [vc addSubview:btn];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(40, 7, 30, 30)];
 
        [img sd_setImageWithURL:[NSURL URLWithString:sectionCar.shopImage]];
      [vc addSubview:img];
    UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(75, 7, WIDE - 100, 20 )];
  
        titleLB.text = sectionCar.shopName;

   
   [vc addSubview:titleLB];
    return vc;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex ==0) {
       
        [self.navigationController popViewControllerAnimated:YES];
     }
    
   
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _sectionIndex = (int)indexPath.section;
}
-(void)selectHeaderBtn:(UIButton *)btn{

      NSMutableDictionary *sectionDict = [_selectArray[btn.tag-10000] objectForKey:[NSString stringWithFormat:@"%dsection",(int)btn.tag - 10000]];
    NSString *  isSeclect = [_selectArray[btn.tag-10000] objectForKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)btn.tag-10000]];
    if ([isSeclect isEqualToString:@"NO"]) {
        [_selectArray[btn.tag -10000] setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)btn.tag-10000]];
        
          CarSection *sectionGoods = self.shoppingCar.sectionArr[btn.tag-10000];
        for (int i = 0; i <sectionDict.allKeys.count; i ++) {
            if ([[sectionDict objectForKey:[NSString stringWithFormat:@"%dsection_%drow",(int)btn.tag-10000,i]]isEqualToString:@"NO"]) {
             
                [sectionDict setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)btn.tag-10000,i]];
               ShoppingCarItem *item = sectionGoods.itemsArr[i];
                [sectionDict setObject:[NSString stringWithFormat:@"%f",item.count*item.discountPrice*0.01] forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)btn.tag - 10000 ,i]];

            }
  
        }
          }else
        {
     
        [_selectArray[btn.tag -10000] setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)btn.tag-10000]];
        for (int i = 0; i < sectionDict.allKeys.count/2; i++) {
        
            [sectionDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)btn.tag - 10000,i]];

            [sectionDict setObject:@"0" forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)btn.tag - 10000 ,i]];
        }
 
    }


   [_tableViewShopping reloadData];
}

-(void)selectBtn:(UIButton *)btn{
    UITableViewCell *cell = (UITableViewCell *)[[btn superview ]superview] ;
    
    NSIndexPath *index = [_tableViewShopping indexPathForCell:cell ];


    NSMutableDictionary *sectionDict = [_selectArray[index.section] objectForKey:[NSString stringWithFormat:@"%dsection",(int)index.section]];
    if ([[sectionDict objectForKey:[NSString stringWithFormat:@"%dsection_%drow",(int)index.section,(int)index.row]] isEqualToString:@"YES"]) {
        btn.selected = NO;
        [btn setImage:[UIImage imageNamed:@"购物车未选择"] forState:UIControlStateNormal];
        [sectionDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)index.section,(int)index.row]];
        [sectionDict setObject:@"0" forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)index.section,(int)index.row]];
       
             }
    else{
        btn.selected = YES;
        [btn setImage:[UIImage imageNamed:@"购物车选中"] forState:UIControlStateSelected];
        [sectionDict setObject:@"YES" forKey:[NSString stringWithFormat:@"%ldsection_%ldrow",index.section,index.row]];
        CarSection *sectionGoods = self.shoppingCar.sectionArr[index.section];
        ShoppingCarItem *item = sectionGoods.itemsArr[index.row];
        
        [sectionDict setObject:[NSString stringWithFormat:@"%.2f",item.count*item.discountPrice*0.01] forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)index.section,(int)index.row]];
 
    }
    
    UIButton * button =(UIButton *)[_tableViewShopping viewWithTag:(10000+index.section)];
    NSMutableDictionary * rowDictionary =[NSMutableDictionary dictionary];
    CarSection *sectionGoods = self.shoppingCar.sectionArr[index.section];

    for (int i = 0; i< sectionGoods.itemsArr.count; i++) {
        [rowDictionary setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_%drow",(int)index.section,i]];
        ShoppingCarItem *item = sectionGoods.itemsArr[i];

        
        [rowDictionary setObject:[NSString stringWithFormat:@"%.2f",item.count*item.discountPrice*0.01] forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int)index.section,i]];
    }
    
    if ([sectionDict isEqualToDictionary:rowDictionary]) {
        [_selectArray[index.section] setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_isSelect",(int)index.section]];
        
        button.selected = YES;
        [button setImage:[UIImage imageNamed:@"购物车选中"] forState:UIControlStateSelected];
        
    }else{
        button.selected = NO;
        [button setImage:[UIImage imageNamed:@"购物车未选择"] forState:UIControlStateNormal];
    }
    
    
    static int a =0;
    _totalPrice = 0.00;
    for ( int r = 0; r< sectionDict.allKeys.count/2; r++) {
        a = [[sectionDict  objectForKey:[NSString stringWithFormat:@"%dsection_%drow_Price",(int )index.section,r]]intValue];
        
        _totalPrice = _totalPrice +a;
     _allPrice.text = [NSString stringWithFormat:@"¥:%.2f",_totalPrice];

     
    }

 
}
- (IBAction)selectAllBtn:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;

    for (int a = 0; a<_selectArray.count; a ++) {
        NSMutableDictionary *sectionDict = [_selectArray[a] objectForKey:[NSString stringWithFormat:@"%dsection",a]];
             
        if (btn.selected) {
            
           [btn setImage:[UIImage imageNamed:@"购物车选中"] forState:UIControlStateSelected];
            [_selectArray[a] setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_isSelect",a]];
                        CarSection *sectionGoods = self.shoppingCar.sectionArr[a];
            for (int i = 0; i <sectionDict.allKeys.count/2; i ++) {
                if ([[sectionDict objectForKey:[NSString stringWithFormat:@"%dsection_%drow",a,i]]isEqualToString:@"NO"]) {
                    
                    [sectionDict setObject:@"YES" forKey:[NSString stringWithFormat:@"%dsection_%drow",a,i]];
                    ShoppingCarItem *item = sectionGoods.itemsArr[i];
                    [sectionDict setObject:[NSString stringWithFormat:@"%d",item.count*item.discountPrice] forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",a ,i]];
                    
                }
                
            }
          
            

        }else
        {
           

            [_selectArray[a] setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_isSelect",a]];
            for (int i = 0; i < sectionDict.allKeys.count/2; i++) {
                
                [sectionDict setObject:@"NO" forKey:[NSString stringWithFormat:@"%dsection_%drow",a,i]];
                
                [sectionDict setObject:@"0" forKey:[NSString stringWithFormat:@"%dsection_%drow_Price",a,i]];
            }
          //  btn.selected = NO;
            [btn setImage:[UIImage imageNamed:@"购物车未选择"] forState:UIControlStateNormal];
        }
       

    }
       [_tableViewShopping reloadData];
    
}
- (IBAction)shoppingJieSuanBtnClick:(id)sender
{
     QueRenDingDanViewController *dingdan = [[QueRenDingDanViewController alloc] init];
    dingdan.shangPinAry = [NSMutableArray array];
 
     ShangPinModel *good = [[ShangPinModel alloc] init];
    for (int a = 0; a <self.shoppingCar.sectionArr.count; a++) {
          CarSection *sectionGoods = self.shoppingCar.sectionArr[a];
        NSMutableDictionary *sectionDict = _selectArray[a];
        
      NSMutableDictionary *rowDict = [sectionDict objectForKey:[NSString stringWithFormat:@"%dsection",a ]];
    
            for (int i = 0; i <sectionDict.allKeys.count; i ++) {
                
                if ([[rowDict objectForKey:[NSString stringWithFormat:@"%dsection_%drow",a ,i]] isEqualToString:@"YES"]) {
                  
                    ShoppingCarItem *item = sectionGoods.itemsArr[i];
                
                   
                    good.name = item.name;
                    good.Id=[NSString stringWithFormat:@"%d",item.itemId];
                    good.productId = [NSString stringWithFormat:@"%d", item.productId];
                    good.image = item.image;
                    good.shuLiang = [NSString stringWithFormat:@"%d", item.count];
                    good.jiaGe = [NSString stringWithFormat:@"%.2f", item.discountPrice*0.01];
                    if ([item.desc length]) {
                        good.chiMa =[item.desc substringFromIndex:2];
                        good.yanSe = [item.desc substringToIndex:2];
                    }else{
                        good.chiMa =@"";
                        good.yanSe = @"";
                    }
                   
                    [dingdan.shangPinAry addObject:good];
                    
                }
            }
        
    }
    

        [self.navigationController pushViewController:dingdan animated:YES];
    
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
